﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PanasonicWarranty.Business;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Text;

namespace PanasonicWarranty.UI
{
    public partial class SentSMS : BasePage
    {
        public string availableTags;
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }


        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindPhoneNumber();
            pagingtop.Visible = pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                PageSize = Convert.ToInt32(ddlSortable_length.SelectedValue);
                pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                pagingtop.PageDisplay = pagingbottom.PageDisplay = 6;
                BindShortCode();
                ddlUnit.Items.Add(new ListItem(DB.pepsi_Units.FirstOrDefault(p => p.ID == CurUser.UnitID).Name, CurUser.UnitID.ToString()));
                BindUnit(CurUser.UnitID, "--");
                BindStaffType();
                BindStaffLevel();
                availableTags = string.Join(",", DB.pepsi_Staffs.Select(p => "\"" + p.StaffName + "\"").ToArray());
                BindPhoneNumber();
            }
        }

        private void BindShortCode()
        {
            ddlShorCode.DataSource = DB.SmsShortCodes.OrderBy(p => p.OrderID);
            ddlShorCode.DataTextField = "ShortCode";
            ddlShorCode.DataValueField = "ShortCode";
            ddlShorCode.DataBind();
        }

        private void BindPhoneNumber()
        {
            Guid? unitId = new Guid(ddlUnit.SelectedValue);
            string staffName = null;
            if (!string.IsNullOrEmpty(txtStaffName.Text.Trim())) staffName = txtStaffName.Text.Trim();
            int? stafftype = ddlStaffType.SelectedValue == "" ? (int?)null : int.Parse(ddlStaffType.SelectedValue);
            int? stafflevel = ddlStaffLevel.SelectedValue == "" ? (int?)null : int.Parse(ddlStaffLevel.SelectedValue);
            bool recursive = chkRecursive.Checked;
            int? currentPage = pagingtop.CurrentPage;
            int? pageSize = pagingtop.PageSize;
            int? totalRecord = 0;
            rptPhone.DataSource = DB.pepsi_PhoneToMessage(unitId, staffName, stafftype, stafflevel, currentPage, pageSize, ref totalRecord, recursive);
            pagingtop.TotalRecord = pagingbottom.TotalRecord = totalRecord.Value;
            pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
            rptPhone.DataBind();
            ltrInfo.Text = "Total pages: " + pagingtop.TotalPage; 
        }

        private void BindUnit(Guid? unitID, string ident)
        {
            var dataSource = DB.pepsi_Units.Where(p => p.ParentID == unitID).OrderBy(p => p.Name);
            foreach (var item in dataSource)
            {
                ddlUnit.Items.Add(new ListItem(ident + item.Name, item.ID.ToString()));
                BindUnit(item.ID, Server.HtmlDecode("&nbsp;&nbsp;&nbsp;") + ident);
            }
        }

        private void BindStaffType()
        {
            ddlStaffType.DataSource = DB.pepsi_StaffTypes.OrderBy(p => p.StaffTypeName);
            ddlStaffType.DataValueField = "StaffTypeID";
            ddlStaffType.DataTextField = "StaffTypeName";
            ddlStaffType.DataBind();
            ddlStaffType.Items.Insert(0, new ListItem("--Choose--", ""));
        }

        private void BindStaffLevel()
        {
            ddlStaffLevel.Items.Add(new ListItem("--Choose--", ""));
            for (int i = 1; i <= 12; i++)
            {
                ddlStaffLevel.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
        }

        private void CheckFullInfo()
        {
            if (string.IsNullOrEmpty(txtMessage.Text.Trim()))
            {
                throw new Exception("Message not allow null!");
            }

        }

        protected void btnSentMessage_Click(object sender, EventArgs e)
        {
            if (IsRefresh) return;
            if (!AllowSendMessage())
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('You don't have permission to sending message!');", true);
                return;
            }
            try
            {
                CheckFullInfo();
                DataTable dtPhoneNumber = new DataTable();
                dtPhoneNumber.Columns.Add("GuidID", typeof(Guid));
                dtPhoneNumber.Columns.Add("VALUE1", typeof(string)).DefaultValue = string.Empty;
                dtPhoneNumber.Columns.Add("VALUE2", typeof(int)).DefaultValue = 1;
                string[] phoneList = hdfPhoneList.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string item in phoneList)
                {
                    dtPhoneNumber.Rows.Add(Guid.NewGuid(), item.Substring(0, item.IndexOf(":")), int.Parse(item.Substring(item.IndexOf(":") + 1)));
                }
                //Added phone number
                phoneList = txtAddedPhoneNumber.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string item in phoneList)
                {
                    string phonenumber = item.ToNormalPhoneNumber();
                    var prefixObj = DB.OperatorPrefixCodes.FirstOrDefault(p => phonenumber.IndexOf(p.prefix_code) == 0);
                    if (prefixObj == null)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Added phone number is invalid!');", true);
                        return;
                    }
                    else if (phonenumber.Length < prefixObj.min_length || phonenumber.Length > prefixObj.max_length)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Added phone number is invalid!');", true);
                        return;
                    }
                    dtPhoneNumber.Rows.Add(Guid.NewGuid(), phonenumber, prefixObj.operator_id ?? -1);
                }
                if (dtPhoneNumber.Rows.Count == 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Phone number to send message must be atleast one!');", true);
                    return;
                }
                using (SqlConnection conn = new SqlConnection(LocalSetting.ConnectionString))
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "pepsi_InsertMessage";
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@MoGuid", DBNull.Value);
                        cmd.Parameters.AddWithValue("@ShortCode", ddlShorCode.SelectedValue);
                        cmd.Parameters.AddWithValue("@DestAddr", dtPhoneNumber);
                        cmd.Parameters.AddWithValue("@Message", txtMessage.Text);
                        cmd.Parameters.AddWithValue("@CooperateID", 1);
                        cmd.Parameters.AddWithValue("@Status", "PENDING");
                        cmd.Parameters.AddWithValue("@SentTime", DateTime.Now);
                        cmd.Parameters.AddWithValue("@CDRIndicator", "FREE");
                        cmd.Parameters.AddWithValue("@MTType", DB.SmsShortCodes.FirstOrDefault(p => p.ShortCode == ddlShorCode.SelectedValue).MTType);
                        cmd.Parameters.AddWithValue("@RetryOnFailReqTimes", 0);
                        cmd.Parameters.AddWithValue("@RetryOnTimeOutReqTimes", 0);
                        cmd.Parameters.AddWithValue("@RetryOnFailReqDuration", 0);
                        cmd.Parameters.AddWithValue("@RetryOnTimeOutReqDuration", 0);
                        cmd.Parameters["@DestAddr"].SqlDbType = SqlDbType.Structured;
                        cmd.Parameters["@DestAddr"].TypeName = "dbo.VARCHAR_TABLE";
                        cmd.ExecuteNonQuery();
                    }
                }
                txtMessage.Text = string.Empty;
                txtAddedPhoneNumber.Text = string.Empty;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Sending message susccessfully!');", true);
            }
            catch(Exception ex)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + ex.Message + "')", true);
            }
        }

        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindPhoneNumber();
        }

        protected void chkRecursive_CheckedChanged(object sender, EventArgs e)
        {
            BindPhoneNumber();
        }

        protected void rptPhone_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                if (e.Item.DataItem != null)
                {
                    HtmlTableCell cell = (HtmlTableCell)e.Item.FindControl("tdPhoneNumber");
                    string[] phoneNumber = (e.Item.DataItem.GetType().GetProperty("PhoneNumber").GetValue(e.Item.DataItem, null) as string).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (phoneNumber.Length > 0)
                    {
                        StringBuilder InnerHtml = new StringBuilder();
                        foreach(string item in phoneNumber)
                        {
                            InnerHtml.AppendLine("<input type='checkbox' value='" + item + "' name='chkPhoneNumber' />");
                            InnerHtml.AppendLine("<label for='chkPhoneNumber'>" + item.Substring(0, item.IndexOf(":")) + "</label><br/>");
                        }
                        cell.InnerHtml = InnerHtml.ToString();
                    }
                }
            }
            catch { }
        }

        protected void ddlSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            PageSize = Convert.ToInt32(ddlSortable_length.SelectedValue);
            pagingtop.PageSize = pagingbottom.PageSize = PageSize;
            BindPhoneNumber();
        }

        protected void ddlStaffType_SelectedIndexChanged(object sender, EventArgs e)
        {
            RebindPhoneNumber();
        }
        
        protected void ddlStaffLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            RebindPhoneNumber();
        }

        protected void txtStaffName_TextChanged(object sender, EventArgs e)
        {
            RebindPhoneNumber();
        }

        void RebindPhoneNumber()
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            BindPhoneNumber();
            pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }
    }
}